package spring.beanDefinitionRegistryPostProcessor;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;

/**
 * Spring 扫描自定义注解：扫描工具类
 *
 * @author ME
 * @date 2021/5/21
 */
@Component
public class CustomAnnotationScanner implements BeanDefinitionRegistryPostProcessor {

	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		String[] beanDefinitionNames = registry.getBeanDefinitionNames();
		System.out.println("=========== 遍历所有`beanDefinitionName` ============\n");
		for(String beanDefinitionName : beanDefinitionNames){
			BeanDefinition beanDefinition = registry.getBeanDefinition(beanDefinitionName);
			System.out.println("bd：" + (beanDefinition.getBeanClassName() != null
					? beanDefinition.getBeanClassName() : beanDefinition.getFactoryBeanName()));
		}
		System.out.println();

		// 定义一个扫描器，按指定过滤规则扫描 Bean（如：扫描自定义注解），并将扫描到的 bean 注册到给定注册器
		ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry);
		scanner.addIncludeFilter(new AnnotationTypeFilter(CustomAnnotation.class));
		scanner.scan(this.getClass().getPackage().getName());
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

	}

}
